package com.alibaba.runner;

import com.alibaba.common.SystemConstants;
import com.alibaba.define.domain.ArticleDO;
import com.alibaba.fastjson.JSON;
import com.alibaba.manager.ArticleManager;
import com.alibaba.utils.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author : hanyang
 * @date : 2023-11-06 23:32
 **/

@Component
@Slf4j
public class ViewCountRunner implements CommandLineRunner {

    @Resource
    ArticleManager articleManager;

    @Resource
    RedisCache redisCache;

    @Override
    public void run(String... args) throws Exception {
        // 查询博客信息 id viewCount
        List<ArticleDO> articleDOS = articleManager.queryArticleIdAndViewCountList();
        if (CollectionUtils.isEmpty(articleDOS)) {
            return;
        }
        log.info("ViewCountRunner ==> run article ViewCount query success! result:{}", JSON.toJSONString(articleDOS));
        // id->viewCount map
        Map<String, Integer> idAndViewCountMap = articleDOS.stream()
                .collect(Collectors.toMap(articleDO1 -> articleDO1.getId().toString(),
                        articleDO -> articleDO.getViewCount().intValue()));
        // 存储到redis
        redisCache.setCacheMap(SystemConstants.ARTICLE_VIEW_COUNT_KEY, idAndViewCountMap);
        log.info("put data to redis success!");
    }
}
